<?php

namespace App\Service\VendorClient\Shopzhaofenghang;

use Service\AppService\IdService;
use App\Service\Code\Normal;
use App\Service\CodeService\UuidBuilderService;
use App\Service\TaskServer\TaskWorker;

class ShopzhaofenghangApiClient
{
    private $account  = 'shopzhaofenghang';
    private $baseurl='http://api.yiwukaicang.com/ywkc/api/openapi/main';
    protected $config;
    private $routers  = [
        'creatOrder'   => 'order_add',
        'cancelOrder'  => 'order_cancel',
        'queryExpress' => 'order_query'
    ];
    /**
     * 初始参数
     * @param array $apiBody
     */
    public function __construct( $apiBody = [] )
    {
        $this->config = $apiBody;
    }

    /**
     * 创建订单
     */
    public function createOrder( $params = [] )
    {
        $orderInfo      = $params['supplierOrder'];
        $orderItem      = $params['orderGoods'];
        $order          = $params['order'];

        //支付流水号
        $pay_sn    = $order['paySerial'] ?? $orderInfo['pay_sn'];
        //运费
        $deliver_money  = $orderInfo['deliver_money'];
        //支付流水号
        $order_sn       = $orderInfo['supplier_dsn'];

        //判断支付方式是否存在
        $apply_extends  = @json_decode($orderInfo['apply_extends'],true);
        $enterpriseNum = $order['enterpriseNum']??$apply_extends['enterpriseNum']??'';

        //组装商品数据列表
        $goodsList          = [];
        $goodsTotalMoney    = 0;
        $way_tax_fee        = 0;
        foreach ($orderItem as $key =>  & $item )
        {
            $tax_rate           = bcadd('1', (string)$item['tax_rate'],4);
            $price              = $item['price'];
            $spec_num           = $item['spec_num'];
            $quantity           = $item['quantity'];
            $buyNum             = $spec_num * $quantity;
            //单价含税单价需要把第三位往上收取，不能单独不含税价和税金分开计算，需要做减法
            $singlePrice        = bcdiv((string)$price, (string)$spec_num,3);
            $singlePrice        = bcmul((string)$singlePrice,'100',1);
            $singlePrice        = bcdiv((string)ceil($singlePrice),'100',2);
            $totalSinglePrice   = bcmul($singlePrice,$buyNum,2);

            //不含税价格
            $notTaxGoodsSinglePrice = bcdiv((string)$singlePrice, $tax_rate,3);
            $notTaxGoodsSinglePrice = bcmul((string)$notTaxGoodsSinglePrice,(string)'100',1);
            $notTaxGoodsSinglePrice = bcdiv((string)ceil($notTaxGoodsSinglePrice),'100',2);


            $goodsTotalPrice    = bcmul((string)$notTaxGoodsSinglePrice,(string)$buyNum,2);

            //商品关税当前币种最小单位（分）
            $goodsCustomsTax    = bcsub((string)$singlePrice,(string)$notTaxGoodsSinglePrice,2);
            $taxAll             = bcmul($goodsCustomsTax,(string)$buyNum,2);

            $goodsInfo = [
                "goods_no"                => $item['supplier_skucode'],
                "number"                  => $buyNum,
                "total"                   => $this->MultiplyByOneHundred($totalSinglePrice),
            ];
            $goodsList[] = $goodsInfo;
            $goodsTotalMoney    = bcadd((string)$goodsTotalMoney,$goodsTotalPrice,2);
            $way_tax_fee        = bcadd((string)$way_tax_fee,$taxAll,2);
        }

        //订单总价（商品保税价格 + 运费）
        $totalMoney             = bcadd((string)$goodsTotalMoney, (string)$deliver_money,2);
        $totalMoney             = bcadd($totalMoney, (string)$way_tax_fee,2);
        //订单优惠金额
        $real_total_money       = $orderInfo['real_total_money'];
        $discount_money         = bcsub((string)$totalMoney,(string)$real_total_money,2);
        //创建订单数据
        $data=[
            'order_no'                   => $order_sn,//订单号
//            'f_shop_id'                  => '',
//            'pdd_shop_id'                => '',
            'create_time'                => date('Y-m-d H:i:s', $orderInfo['cd']),
            'pay_time'                   => date('Y-m-d H:i:s', time()),
            'total_price'                => $this->MultiplyByOneHundred($real_total_money),
            'total_tax'                  => $this->MultiplyByOneHundred($way_tax_fee),
            'total_fright'               => $this->MultiplyByOneHundred($deliver_money),
            'f_discount'                 => $this->MultiplyByOneHundred($discount_money),
            'customs'                    => [
                'idcard'                     => $orderInfo['buyer_idcard'],
                'idcard_name'                => $orderInfo['buyer_realname'],
                'plaform_code'               => $order['enterpriseNum'] ?? $apply_extends['enterpriseNum'] ?? '',
                'pay_id'                     => $order['payCommanyCode']?? $apply_extends['payCommanyCode'] ?? '',
                'pay_no'                     => $pay_sn,
                'order_decla_no'             => $order_sn,
            ],
            'address'                    => [
                'consignee'                  => $orderInfo['receive_name'],
                'consignee_phone'            => $orderInfo['recveive_phone'],
                'province'                   => $orderInfo['province'],
                'city'                       => $orderInfo['city'],
                'area'                       => $orderInfo['district'],
                'address'                    => $orderInfo['receive_address'],
            ],
            'goods'                        => $goodsList
        ];

        $requestParam = [
            'method'    => 'creatOrder',
            'data'      => $data,
        ];
        return $this->execute($requestParam);

    }

    /**
     * 取消订单
     */
    public function cancelOrder($params = []) {
        $requestParam = [
            'method'    => 'cancelOrder',
            'data'      => [
                'order_no' => $params['supplierOrder']['supplier_dsn'],
                'order_decla_no' => $params['supplierOrder']['supplier_dsn'],
            ],
        ];
        return $this->execute($requestParam);
    }

    /**
     * 获取发货物流信息
     */
    public function queryOrderExpress( $param = [] )
    {
        return Normal::returnCode(Normal::SUC,"处理完成");
    }

    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute( $param = [] )
    {
        if( empty($param['data']) ) {
            return Normal::returnCode(Normal::FAIL,"数据不能为空");
        }

        $method = $param['method'];
        $route = $this->routers[$method];
        $requestData=[
            'warehouse_no' => $this->config['warehouse_no'] ?? '',
            'charset'      => $this->config['charset'] ?? 'UTF-8',
            'customer_no'  => $this->config['customer_no'] ?? '',
            'nonce_str'    => UuidBuilderService::instance()->getCode(),
            'method'       => $route,
            'sign_type'    => $this->config['sign_type'] ?? 'MD5',
            'query_params' => json_encode($param['data'],JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE)
        ];
        $requestData['sign']=$this->getSign($requestData);
        $parameter = [
            [
                'tag'       => $this->account.'_'.$method,
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => $this->baseurl,
                'data'      => $requestData,
                'method'    => 'post',
                'format'    => 'form-data',
                'header'    => [],
            ],
        ];
        $resTask = TaskWorker::instance()->addTask($parameter);
        $resTask = current($resTask);
        $res     = $resTask['response']['result'];
        $resHttp = json_decode($res,true);
        if( isset($resHttp['errorCode']) && $resHttp['errorCode'] == 0 ) {
            return Normal::returnCode(Normal::SUC,"操作成功",$resHttp);
        }
        $message = isset($resHttp['errorMsg']) ? $resHttp['errorMsg'] : '请求失败';
        return Normal::returnCode(Normal::FAIL,$message);
    }

    /**
     * 获取sign参数
     */
    private function getSign($param = []) {
        ksort($param);
        $arr = [];
        foreach ($param as $k => $v) {
            $arr[] = "{$k}={$v}";
        }
        $str = implode("&", $arr);
        $str = $str . $this->config['secret'];
        return strtoupper(md5($str));
    }

    /**
     * 转换为分
     * @return string
     */
    private function MultiplyByOneHundred($money)
    {
        return bcmul($money,100);
    }

}